import {DeviceEventEmitter, ToastAndroid} from 'react-native';
import {LOGIN, STORE} from '../type';
import { getNowFormatDate } from '../../utils'
import axios from 'axios';
import Http from '../../net'
import Tips from "react-native-root-tips";



const userLogin = (userName, password, callback) => async (dispatch, getState) => {
    axios.post('api/v2/shop/login', {
        username: userName,
        password: password
    }).then(res => {
        res = res.data;
        if (res.status) {
            const getNowDate = getNowFormatDate();
            let token = res.data.token_type + ' ' + res.data.access_token;
            storage.save({
               key: 'user-token',
               data: token
            });
            if (res.data.clerk) {
                storage.save({
                    key: 'clerk-info',
                    data: res.data.clerk
                })
            }
            storage.save({
                key: 'login-time',
                data: getNowDate
            });

            DeviceEventEmitter.emit('userLogin', true);
        } else {
            DeviceEventEmitter.emit('userLogin', false, res.message || '请求失败');
        }
    }, err => {
        alert(err);
        DeviceEventEmitter.emit('userLogin', false, '请求失败');
    });
};
// 获取交接班详情
const getStatisticsDetail = (callback) => async (dispatch, getState) => {
    const token = await storage.load({
        key: 'user-token'
    }).then(res => {
        return res;
    });
    Tips.showLoading('加载中', {mask: true, maskColor:'gray'});
    const res = await axios.get('api/v2/shop/statistics', {
        headers: {
            Authorization: token
        }

    }).then(res => {
        Tips.hide();
        res = res.data;
        if (res.status) {
            if (res.data) {
                dispatch({
                    type: LOGIN.STATISTICS_DETAIL,
                    res: res.data
                })
            }
        } else {
            Tips.showFail(res.message || '请求失败')
        }
        return res
    }, err => {
        Tips.hide();
        Tips.showFail('请求失败');
        return err
    });
    callback && callback(res);
};


export default {
    userLogin,
    getStatisticsDetail
}